//科目状态---有效
var state_valid = "1";
//科目状态---无效
var state_invalid = "0";
//#物品在库
var state_incoming = "1";
//#物品出库
var state_outcoming = "0";
//#物品报废
var state_scrap = 2;

$(function () {
    //1.初始化Table
    var oTable = new TableInit();
    oTable.Init();

    //2.初始化Button的点击事件
    var oButtonInit = new ButtonInit();
    oButtonInit.Init();

    $('#outcoming_lendTime').datetimepicker({
        language: 'en',
        pickerPosition: 'top-right',
        autoclose: true,
        todayBtn: true,
        todayHighlight: true,
        showMeridian: true,
        linkField: 'outcoming_datetime'
    });
    $('#incoming_returnTime').datetimepicker({
        language: 'en',
        pickerPosition: 'top-right',
        autoclose: true,
        todayBtn: true,
        todayHighlight: true,
        showMeridian: true,
        linkField: 'incoming_datetime'
    });
});

var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $('#tb_table_list').bootstrapTable("destroy");
        $('#tb_table_list').bootstrapTable({
            url: 'itemInfoController/showItemTypeList',         //请求后台的URL（*）
            method: 'get',                                      //请求方式（*）
            toolbar: '#toolbar',                                //工具按钮用哪个容器
            striped: true,                                      //是否显示行间隔色
            cache: false,                                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                                   //是否显示分页（*）
            sortable: false,                                    //是否启用排序
            sortOrder: "asc",                                   //排序方式
            queryParams: oTableInit.queryParams,                //传递参数（*）
            sidePagination: "server",                           //分页方式：client客户端分页，server服务端分页（*）
            queryParamsType: "undefined",                       //设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
                                                                //设置为limit可以获取limit, offset, search, sort, order
            pageNumber: 1,                                      //初始化加载第一页，默认第一页
            pageSize: 10,                                       //每页的记录行数（*）
            pageList: [10],                                     //可供选择的每页的行数（*）
            search: false,                                      //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: true,
            showColumns: false,                                 //是否显示所有的列
            showRefresh: false,                                 //是否显示刷新按钮
            minimumCountColumns: 2,                             //最少允许的列数
            clickToSelect: true,                                //是否启用点击选中行
            height: 550,                                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "ID",                                     //每一行的唯一标识，一般为主键列
            showToggle: false,                                  //是否显示详细视图和列表视图的切换按钮
            cardView: false,                                    //是否显示详细视图
            detailView: false,                                  //是否显示父子表
            columns: [{
                checkbox: true,
                align: 'center'
            }, {
                field: 'itemInfoNum',
                title: '编号',
                align: "center"
            }, {
                field: 'subjectName',
                title: '科目',
                align: "center"
            }, {
                field: 'itemName',
                title: '品名',
                align: "center"
            }, {
                field: 'itemNum',
                title: '货号',
                align: "center"
            }, /*{
             field: 'quantity',
             title: '数量',
             align: "center"
             },*/ {
                field: 'price',
                title: '单价',
                align: "center"
            }, {
                field: 'state',
                title: '状态',
                align: 'center',
                formatter: function (value, row, index) {
                    if (row.state == '0') return "<span style='color:#FF3030'>出库</span>";
                    if (row.state == '1') return "<span style='color:#66CD00'>在库</span>";

                }
            }],
            //双击列表行打开查看详细页面
            onDblClickRow: function (row, $element, field) {
                $.post("itemInfoController/showItemInfoWithItemUse", {itemInfoId: row.id}, function (data) {
                    $("#showModalLabel").text("查看物品信息");
                    $("#show_subjectName").val(data["itemUse"].subjectName);
                    $("#show_itemName").val(data["itemUse"].itemName);
                    $("#show_quantity").val(data["itemUse"].quantity);
                    $("#show_price").val(data["itemUse"].price);
                    $("#show_itemInfoNum").val(data["itemUse"].itemInfoNum);
                    $("#show_remark").val(data["itemUse"].remark);
                    $(":radio[name='show_state'][value='" + data["itemUse"].state + "']").prop("checked", "checked");

                    if (data["count"] > 0) {
                        $("#show_lender").val(data["itemUse"].receiptorId);
                        $("#show_lendTime").val(data["itemUse"].getTime);
                        $("#show_lendRemark").val(data["itemUse"].receiptorRemark);

                        $("#show_returner").val(data["itemUse"].returnedId);
                        $("#show_returnTime").val(data["itemUse"].returnTime);
                        $("#show_returnedRemark").val(data["itemUse"].returnedRemark);
                    }

                    $('#showPage').modal();
                });
            }
        });
    };

    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {                        //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            currentPage: params.pageNumber,
            PAGE_SIZE: params.pageSize,
            subjectName: $("#search_subjectName").val(),
            itemName: $("#search_itemName").val(),
            itemInfoNum: $("#search_itemInfoNum").val(),
            state: $("#search_state").val()
        };
        return temp;
    };
    return oTableInit;
};


var ButtonInit = function () {
    var oInit = new Object();

    oInit.Init = function () {
        <!-- =============================列表查询和重置开始=============================-->
        //列表页面查询
        $("#btn_query").click(function () {
            var oTable = new TableInit();
            oTable.Init();
        });

        //清空查询框内容
        $("#btn_resert").click(function () {
            $("#search_subjectName").val("");
            $("#search_itemName").val("");
            $("#search_itemInfoNum").val("");
            $("#search_state").val("");
        });
        <!-- =============================列表查询和重置结束=============================-->

        <!-- =============================数据修改、出库、入库和停用开始=============================-->
        //列表页面修改
        $("#btn_edit").click(function () {
            var selectors = $.map($("#tb_table_list").bootstrapTable('getSelections'), function (row) {
                return row.id;
            });
            if (selectors.length == 0) {
                alert("请选择您要修改的物品!");
                return;
            } else if (selectors.length > 1) {
                alert("请您选择一项物品进行修改!");
                return;
            } else {
                $.post("itemInfoController/showItemInfo", {id: selectors.toString()}, function (data) {
                    $("#modifyModalLabel").text("修改物品信息");

                    $("#modify_subjectName").val(data["itemInfo"].subjectName);
                    $("#modify_itemName").val(data["itemInfo"].itemName);
                    $("#modify_itemNum").val(data["itemInfo"].itemNum);
                    $("#modify_quantity").val(data["itemInfo"].quantity);
                    $("#modify_price").val(data["itemInfo"].price);
                    $("#modify_itemInfoNum").val(data["itemInfo"].itemInfoNum);
                    $("#modify_remark").val(data["itemInfo"].remark);
                    $(":radio[name='modify_state'][value='" + data["itemInfo"].state + "']").prop("checked", "checked");

                    $("#id").val(data["itemInfo"].id);
                    $("#itemTypeId").val(data["itemInfo"].itemTypeId);

                    $('#modifyPage').modal();
                });
            }
        });

        //列表页面出库
        $("#btn_outcoming").click(function () {
            var selectors = $.map($("#tb_table_list").bootstrapTable('getSelections'), function (row) {
                return row.id;
            });
            if (selectors.length == 0) {
                alert("请选择您要出库的的物品!");
                return;
            } else if (selectors.length > 1) {
                alert("请您选择一项物品进行出库!");
                return;
            } else {
                var state = $.map($("#tb_table_list").bootstrapTable('getSelections'), function (row) {
                    return row.state;
                });
                if (state == state_outcoming) {
                    alert("请您选择状态为在库的物品进行出库操作!");
                    return;
                }
                $.post("itemInfoController/showItemInfo", {id: selectors.toString()}, function (data) {
                    $("#outcomingModalLabel").text("登记物品出库信息");

                    $("#outcoming_subjectName").val(data["itemInfo"].subjectName);
                    $("#outcoming_itemName").val(data["itemInfo"].itemName);
                    $("#outcoming_itemNum").val(data["itemInfo"].itemNum);
                    $("#outcoming_quantity").val(data["itemInfo"].quantity);
                    $("#outcoming_price").val(data["itemInfo"].price);
                    $("#outcoming_itemInfoNum").val(data["itemInfo"].itemInfoNum);
                    $("#outcoming_remark").val(data["itemInfo"].remark);
                    $(":radio[name='outcoming_state'][value='" + data["itemInfo"].state + "']").prop("checked", "checked");

                    //初始化领用时间
                    var currentDate = new Date();
                    var currentDateYear = currentDate.getFullYear();
                    var currentDateMonth = currentDate.getMonth() + 1;
                    currentDateMonth = (currentDateMonth < 9) ? "0" + currentDateMonth : currentDateMonth;
                    var currentDateDate = currentDate.getDate();
                    currentDateDate = (currentDateDate < 9) ? "0" + currentDateDate : currentDateDate;
                    var currentDateHours = currentDate.getHours();
                    currentDateHours = (currentDateHours < 9) ? "0" + currentDateHours : currentDateHours;
                    var currentDateMinutes = currentDate.getMinutes();
                    currentDateMinutes = (currentDateMinutes < 9) ? "0" + currentDateMinutes : currentDateMinutes;

                    var currentDateString = currentDateYear + "-" + currentDateMonth + "-" + currentDateDate
                        + " " + currentDateHours + ":" + currentDateMinutes;

                    $("#outcoming_lendTime").val(currentDateString);
                    $("#outcoming_id").val(data["itemInfo"].id);
                    $("#outcoming_itemTypeId").val(data["itemInfo"].itemTypeId);
                    $('#outcomingPage').modal();
                });
            }
        });

        //列表页面入库
        $("#btn_incoming").click(function () {
            var selectors = $.map($("#tb_table_list").bootstrapTable('getSelections'), function (row) {
                return row.id;
            });
            if (selectors.length == 0) {
                alert("请选择您要入库的的物品!");
                return;
            } else if (selectors.length > 1) {
                alert("请您选择一项物品进行入库!");
                return;
            } else {
                var state = $.map($("#tb_table_list").bootstrapTable('getSelections'), function (row) {
                    return row.state;
                });
                if (state == state_incoming) {
                    alert("请您选择状态为出库的物品进行入库操作!");
                    return;
                }
                $.post("itemInfoController/showItemUse", {id: selectors.toString()}, function (data) {
                    $("#incomingModalLabel").text("登记物品入库信息");

                    $("#incoming_subjectName").val(data["itemUse"].subjectName);
                    $("#incoming_itemName").val(data["itemUse"].itemName);
                    $("#incoming_price").val(data["itemUse"].price);
                    $("#incoming_itemInfoNum").val(data["itemUse"].itemInfoNum);
                    $("#incoming_remark").val(data["itemUse"].remark);
                    $(":radio[name='incoming_state'][value='" + data["itemUse"].state + "']").prop("checked", "checked");

                    $("#incoming_id").val(data["itemUse"].id);
                    $("#incoming_itemInfoId").val(data["itemUse"].itemInfoId);
                    $("#incoming_lendTime").val(data["itemUse"].getTime);
                    $("#incoming_lender").val(data["itemUse"].receiptorId);
                    $("#incoming_lendRemark").val(data["itemUse"].receiptorRemark);

                    //初始化归还时间
                    var currentDate = new Date();
                    var currentDateYear = currentDate.getFullYear();
                    var currentDateMonth = currentDate.getMonth() + 1;
                    currentDateMonth = (currentDateMonth < 9) ? "0" + currentDateMonth : currentDateMonth;
                    var currentDateDate = currentDate.getDate();
                    currentDateDate = (currentDateDate < 9) ? "0" + currentDateDate : currentDateDate;
                    var currentDateHours = currentDate.getHours();
                    currentDateHours = (currentDateHours < 9) ? "0" + currentDateHours : currentDateHours;
                    var currentDateMinutes = currentDate.getMinutes();
                    currentDateMinutes = (currentDateMinutes < 9) ? "0" + currentDateMinutes : currentDateMinutes;

                    var currentDateString = currentDateYear + "-" + currentDateMonth + "-" + currentDateDate
                        + " " + currentDateHours + ":" + currentDateMinutes;

                    $("#incoming_returnTime").val(currentDateString);

                    $('#incomingPage').modal();
                });
            }
        });

        //列表页面停用
        $("#btn_invalid").click(function () {
            var selectors = $.map($("#tb_table_list").bootstrapTable('getSelections'), function (row) {
                return row.id;
            });
            if (selectors.length == 0) {
                alert("请选择您要停用的物品!");
                return;
            }
            $.post("itemInfoController/updateState", {ids: selectors.toString(), state: state_scrap}, function () {
                var oTable = new TableInit();
                oTable.Init();
            });
        });
        <!-- =============================数据修改、出库、入库和停用结束=============================-->

        <!-- =============================修改开始=============================-->
        //修改页面保存按钮
        $("#btn_modifySubmit").click(function () {
            $('#modify-form').bootstrapValidator('validate');
            var bootstrapValidator = $('#modify-form').data('bootstrapValidator');
            //表单验证通过
            if (bootstrapValidator.isValid()) {
                var itemInfoNum = $("#modify_itemInfoNum").val().trim();
                var remark = $("#modify_remark").val().trim();
                var id = $("#id").val();
                var itemTypeId = $("#itemTypeId").val();
                $.post("itemInfoController/checkItemInfoNum", {
                    itemInfoNum: itemInfoNum,
                    remark: remark,
                    itemTypeId: itemTypeId,
                    id: id
                }, function (data) {
                    if (data.count != 0) {
                        alert("您修改后的编号已存在!");
                    } else {
                        $.post("itemInfoController/updateItemInfo", {
                            itemInfoNum: itemInfoNum,
                            remark: remark,
                            id: id
                        }, function () {
                            var oTable = new TableInit();
                            oTable.Init();
                        });
                        //隐藏弹出修改页面
                        $("#modifyPage").modal("hide");
                        $("#modify-form").bootstrapValidator('resetForm', true);
                    }
                });
            }
        });

        //修改页面关闭按钮
        $('#btn_modifyClose').click(function () {
            $("#modifyPage").modal("hide");
            $("#modify-form").bootstrapValidator('resetForm', true);
        });
        <!-- =============================修改结束=============================-->


        <!-- =============================出库开始=============================-->
        //添加页面保存按钮
        $("#btn_outcomingSubmit").click(function () {
            $('#outcoming-form').bootstrapValidator('validate');
            var bootstrapValidator = $('#outcoming-form').data('bootstrapValidator');
            //表单验证通过
            if (bootstrapValidator.isValid()) {
                var lender = $("#outcoming_lender").val().trim();
                var dateTime = $("#outcoming_datetime").val().trim();
                if (dateTime == "")
                    dateTime = $("#outcoming_lendTime").val().trim() + ":00";
                var remark = $("#outcoming_lendRemark").val().trim();

                var id = $("#outcoming_id").val().trim();
                $.post("itemInfoController/addItemUseInfo", {
                    receiptorId: lender,
                    getTime: dateTime,
                    receiptorRemark: remark,

                    id: id
                }, function () {
                    var oTable = new TableInit();
                    oTable.Init();
                    //隐藏弹出添加页面
                    $("#outcomingPage").modal("hide");
                    $("#outcoming_lender").val("");
                    $("#outcoming_lendTime").val("");
                    $("#outcoming_lendRemark").val("");
                    $("#outcoming_id").val("");
                    $("#outcoming_datetime").val("");
                    $("#outcoming_itemTypeId").val("");
                    $("#outcoming-form").bootstrapValidator('resetForm', true);
                });

            }
        });


        //添加页面关闭按钮
        $('#btn_outcomingClose').click(function () {
            $("#outcomingPage").modal("hide");
            $("#outcoming_lender").val("");
            $("#outcoming_lendTime").val("");
            $("#outcoming_lendRemark").val("");
            $("#outcoming_id").val("");
            $("#outcoming_datetime").val("");
            $("#outcoming_itemTypeId").val("");
            $("#outcoming-form").bootstrapValidator('resetForm', true);
        });
        <!-- =============================出库结束=============================-->

        <!-- =============================入库开始=============================-->
        //添加页面保存按钮
        $("#btn_incomingSubmit").click(function () {
            $('#incoming-form').bootstrapValidator('validate');
            var bootstrapValidator = $('#incoming-form').data('bootstrapValidator');
            //表单验证通过
            if (bootstrapValidator.isValid()) {
                var returner = $("#incoming_returner").val().trim();
                var dateTime = $("#incoming_datetime").val().trim();
                if (dateTime == "")
                    dateTime = $("#incoming_returnTime").val().trim() + ":00";
                var remark = $("#incoming_returnedRemark").val().trim();

                var id = $("#incoming_id").val().trim();
                var itemInfoId = $("#incoming_itemInfoId").val().trim();
                $.post("itemInfoController/updateItemUseInfo", {
                    returnedId: returner,
                    returnTime: dateTime,
                    returnedRemark: remark,

                    id: id,
                    itemInfoId: itemInfoId
                }, function () {
                    var oTable = new TableInit();
                    oTable.Init();
                    //隐藏弹出添加页面
                    $("#incomingPage").modal("hide");
                    $("#incoming-form").bootstrapValidator('resetForm', true);
                });

            }
        });


        //添加页面关闭按钮
        $('#btn_incomingClose').click(function () {
            $("#incomingPage").modal("hide");
            $("#incoming-form").bootstrapValidator('resetForm', true);
        });
        <!-- =============================入库结束=============================-->

        <!-- =============================查看开始=============================-->
        //查看页面关闭按钮
        $('#btn_showClose').click(function () {
            $("#show_lender").val("");
            $("#show_lendTime").val("");
            $("#show_lendRemark").val("");

            $("#show_returner").val("");
            $("#show_returnTime").val("");
            $("#show_returnedRemark").val("");
            $("#showPage").modal("hide");
        });
        <!-- =============================查看结束=============================-->

        <!-- =============================退出登录开始=============================-->
        $("#logout-button").click(function () {
            $.post("loginController/loginOut", {}, function (data) {
                window.location.href = "login.html";
            });
        });
        <!-- =============================退出登录结束=============================-->
    };
    return oInit;
};